package admin

import (
	"SlowAdmin/controllers"
	"SlowAdmin/models"
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"strconv"
)

// MenuController 菜单控制器
type MenuController struct {
	controllers.BaseController
}

var adminMenuModel models.AdminMenu

// @title 添加
func (c *MenuController) Store() {
	var data struct {
		Apis []string `json:"apis"`
	}
	json.Unmarshal(c.Ctx.Input.RequestBody, &data)
	json.Unmarshal(c.Ctx.Input.RequestBody, &adminMenuModel)

	var apis []models.AdminApi
	for _, item := range data.Apis {
		var temp models.AdminApi
		id, _ := strconv.Atoi(item)
		temp.Id = uint(id)
		apis = append(apis, temp)
	}
	adminMenuModel.Apis = apis

	err := adminMenuModel.Store()

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("添加成功", nil)
}

// @title 获取列表
func (c *MenuController) List() {
	list, err := adminMenuModel.TreeList()

	if err != nil {
		logs.Error(err)
	}

	c.Success("ok", list)
}

// @title 删除
func (c *MenuController) Delete() {
	json.Unmarshal(c.Ctx.Input.RequestBody, &adminMenuModel)

	err := adminMenuModel.Delete()

	if err != nil {
		c.Fail("删除失败", controllers.Result{
			"error": err.Error(),
		})
		return
	}

	c.Success("删除成功", nil)
}

// @title 编辑
func (c *MenuController) Update() {
	var data struct {
		Apis []string `json:"apis"`
	}
	json.Unmarshal(c.Ctx.Input.RequestBody, &data)
	json.Unmarshal(c.Ctx.Input.RequestBody, &adminMenuModel)

	var apis []models.AdminApi
	for _, item := range data.Apis {
		var temp models.AdminApi
		id, _ := strconv.Atoi(item)
		temp.Id = uint(id)
		apis = append(apis, temp)
	}
	adminMenuModel.Apis = apis

	err := adminMenuModel.Update()

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("更新成功", nil)
}

// @title api数据
func (c *MenuController) ApiList() {
	apiModel := models.AdminApi{}

	list := apiModel.GetOptions()

	c.Success("ok", list)
}
